/*
 * @Author: 赵东选 1807248216@qq.com
 * @Date: 2024-10-24 17:20:30
 * @LastEditors: 赵东选 1807248216@qq.com
 * @LastEditTime: 2024-10-26 13:51:45
 * @FilePath: /10_epittimer/bsp/epit/bsp_epit.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置
 * 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "bsp_epit.h"
#include "../int/bsp_inc.h"
#include "../led/bsp_led.h"

/// @brief EPIT1定时器初始化 比较值设置为0
/// @param frac 分频值
/// @param value 加载值
void epit1_init(u32 frac, u32 value) {
  if (frac > 4095) {
    frac = 4095;
  }

  /* 配置EPIT1_CR寄存器 */
  EPIT1->CR = 0;
  // EPIT_CR_ENMOD(1)
  EPIT1->CR |= (0x1 << 1);
  // EPIT_CR_OCIEN(1)
  EPIT1->CR |= (0x1 << 2);
  // EPIT_CR_RLD(1)
  EPIT1->CR |= (0x1 << 3);
  // EPIT_CR_PRESCALAR()
  EPIT1->CR |= (frac << 4);
  // EPIT_CR_CLKSRC(1)
  EPIT1->CR |= (0x1 << 24);

  /* 配置EPIT1_LR寄存器*/
  // EPIT_LR_LOAD(value)
  EPIT1->LR = value;

  /* 配置比较寄存器*/
  // EPIT_CMPR_COMPARE(0);
  EPIT1->CMPR = 0;

  /* 初始化中断*/
  GIC_EnableIRQ(EPIT1_IRQn);

  /* 注册中断服务函数*/
  system_register_irqhandler(EPIT1_IRQn, epit1_irqhandler, NULL);

  /* 开启EPIT1*/
  EPIT1->CR |= (1 << 0);
}

void epit1_irqhandler(unsigned int giccIar, void *param) {
  static u8 state = 0;
  state = !state;
  if (EPIT1->SR & (1 << 0)) {
    led_switch(LED0, state);
  }
  /* 清除中断标志位*/
  EPIT1->SR |= (1 << 0);
}
